//
//  KKPurchaseManager.m
//  KKSDK
//
//  Created by jay Win on 2019/8/16.
//  Copyright © 2019 jay Win. All rights reserved.
//

#import "KKPurchaseManager.h"
#import <RMStore.h>
@interface KKPurchaseManager()<SKPaymentTransactionObserver,RMStoreObserver>
@property BOOL showLog;
@property Boolean isInit;
@property(nonatomic,copy)void(^onComplete)(NSString *);
@end

@implementation KKPurchaseManager
+ (instancetype)shareManager{
    static KKPurchaseManager *manager=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [KKPurchaseManager new];
    });
    return manager;
}
-(void)log:(NSString *)content{
    if(_showLog)
        NSLog(@"======kk=======%@",content);
}
- (NSString *)dictToJSONString:(NSObject*)dic {
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return jsonString;
}
-(void)test{
    
    // ["{\"productIdentifier\":\"com.tapque.p1\",\"purchasetype\":0}","{\"productIdentifier\":\"com.tapque.p2\",\"purchasetype\":2}","{\"productIdentifier\":\"com.tapque.p3\",\"purchasetype\":1}"]


    
    
}

- (void)initPurchase:(BOOL)showLog allInfo:(NSSet *)productInfos completion:(void (^)(NSString * _Nonnull))onComplete{
    if(_isInit)
        return;
    if(SKPaymentQueue.canMakePayments){
        NSLog(@"====================1111111");
    }else{
           NSLog(@"====================22222");
    
    }
    _showLog=showLog;
    _onComplete=onComplete;
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    [[RMStore defaultStore]addStoreObserver:self];
    if(productInfos){
        [self log:[NSString stringWithFormat:@"查询所有商品信息%@",productInfos.description]];
        [[RMStore defaultStore]requestProducts:productInfos success:^(NSArray *products, NSArray *invalidProductIdentifiers) {
            for (int i=0; i>invalidProductIdentifiers.count; i++) {
                [self log:[NSString stringWithFormat:@"查询时存在无效的商品%@",[invalidProductIdentifiers objectAtIndex:i]]];
            }
            if(products){
                NSString *currencySymbol=@"$";
                NSString *tempProductID=[productInfos anyObject];
                __block SKProduct *tempSKProduct= [[RMStore defaultStore] productForIdentifier:tempProductID];
                NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc]init];
                numberFormatter.usesSignificantDigits = true;
                numberFormatter.maximumSignificantDigits = 100;
                numberFormatter.groupingSeparator = @"";
                numberFormatter.numberStyle = NSNumberFormatterDecimalStyle;
                numberFormatter.locale = tempSKProduct.priceLocale;
                //遍历所有商品信息
                NSMutableArray * result=[NSMutableArray array];
                for (
                     SKProduct *item in products) {
                    NSLog(@"====item=====%@",item.description);
                    NSMutableDictionary *itemInfo = [NSMutableDictionary dictionary];
                    itemInfo[@"productIdentifier"]=item.productIdentifier;//id
                    itemInfo[@"price"]=[currencySymbol stringByAppendingString:[numberFormatter stringFromNumber:tempSKProduct.price]];
                    itemInfo[@"localeIdentifier"]=[tempSKProduct.priceLocale localeIdentifier];
                    if (@available(iOS 10.0, *)) {
                        currencySymbol = tempSKProduct.priceLocale.currencySymbol;
                    }else{
                        currencySymbol = numberFormatter.internationalCurrencySymbol;
                    }
                    [result addObject:itemInfo];
                }
                NSDictionary *dic = @{@"Action":@"query",@"Data":[self dictToJSONString:result]};
                self->_onComplete([self dictToJSONString:dic]);
            }else{
                [self log:@"尚未查到任何有效的商品信息"];
            }
        } failure:^(NSError *error) {
            [self log:[NSString stringWithFormat:@"查询信息失败%@",error.localizedDescription]];
        }];
    }else{
        [self log:@"查询时，传入的商品id为空"];
    }
}

- (void)query:(NSSet *)productInfos callback:(void (^)(NSString * _Nonnull))onComplete{
    _onComplete=onComplete;
    if(productInfos){
        [self log:[NSString stringWithFormat:@"查询所有商品信息%@",productInfos.description]];
        [[RMStore defaultStore]requestProducts:productInfos success:^(NSArray *products, NSArray *invalidProductIdentifiers) {
            for (int i=0; i>invalidProductIdentifiers.count; i++) {
                [self log:[NSString stringWithFormat:@"查询时存在无效的商品%@",[invalidProductIdentifiers objectAtIndex:i]]];
            }
            if(products){
                NSString *currencySymbol=@"$";
                NSString *tempProductID=[productInfos anyObject];
                __block SKProduct *tempSKProduct= [[RMStore defaultStore] productForIdentifier:tempProductID];
                NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc]init];
                numberFormatter.usesSignificantDigits = true;
                numberFormatter.maximumSignificantDigits = 100;
                numberFormatter.groupingSeparator = @"";
                numberFormatter.numberStyle = NSNumberFormatterDecimalStyle;
                numberFormatter.locale = tempSKProduct.priceLocale;
                //遍历所有商品信息
                NSMutableArray * result=[NSMutableArray array];
                for (
                     SKProduct *item in products) {
                    NSLog(@"====item=====%@",item.description);
                    NSMutableDictionary *itemInfo = [NSMutableDictionary dictionary];
                    itemInfo[@"productIdentifier"]=item.productIdentifier;//id
                    itemInfo[@"price"]=[currencySymbol stringByAppendingString:[numberFormatter stringFromNumber:tempSKProduct.price]];
                    itemInfo[@"localeIdentifier"]=[tempSKProduct.priceLocale localeIdentifier];
                    if (@available(iOS 10.0, *)) {
                        currencySymbol = tempSKProduct.priceLocale.currencySymbol;
                    }else{
                        currencySymbol = numberFormatter.internationalCurrencySymbol;
                    }
                    [result addObject:itemInfo];
                }
                NSDictionary *dic = @{@"Action":@"query",@"Data":[self dictToJSONString:result]};
                self->_onComplete([self dictToJSONString:dic]);
            }else{
                [self log:@"尚未查到任何有效的商品信息"];
            }
        } failure:^(NSError *error) {
            [self log:[NSString stringWithFormat:@"查询信息失败%@",error.localizedDescription]];
        }];
    }else{
        [self log:@"查询时，传入的商品id为空"];
    }
    
    
    
}



- (void)queryProducts:(NSSet *)productInfos{
    if(productInfos){
        [self log:[NSString stringWithFormat:@"查询所有商品信息%@",productInfos.description]];
        [[RMStore defaultStore]requestProducts:productInfos success:^(NSArray *products, NSArray *invalidProductIdentifiers) {
            for (int i=0; i>invalidProductIdentifiers.count; i++) {
                [self log:[NSString stringWithFormat:@"查询时存在无效的商品%@",[invalidProductIdentifiers objectAtIndex:i]]];
            }
            if(products){
                NSString *currencySymbol=@"$";
                NSString *tempProductID=[productInfos anyObject];
                __block SKProduct *tempSKProduct= [[RMStore defaultStore] productForIdentifier:tempProductID];
                NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc]init];
                numberFormatter.usesSignificantDigits = true;
                numberFormatter.maximumSignificantDigits = 100;
                numberFormatter.groupingSeparator = @"";
                numberFormatter.numberStyle = NSNumberFormatterDecimalStyle;
                numberFormatter.locale = tempSKProduct.priceLocale;
                //遍历所有商品信息
                NSMutableArray * result=[NSMutableArray array];
                for (SKProduct *item in products) {
                    NSMutableDictionary *itemInfo = [NSMutableDictionary dictionary];
                    itemInfo[@"productIdentifier"]=item.productIdentifier;//id
                    itemInfo[@"price"]=[currencySymbol stringByAppendingString:[numberFormatter stringFromNumber:tempSKProduct.price]];
                    itemInfo[@"localeIdentifier"]=[tempSKProduct.priceLocale localeIdentifier];
                    if (@available(iOS 10.0, *)) {
                        currencySymbol = tempSKProduct.priceLocale.currencySymbol;
                    }else{
                        currencySymbol = numberFormatter.internationalCurrencySymbol;
                    }
                    
                    [result addObject:itemInfo];
                }
               

            }else{
                [self log:@"尚未查到任何有效的商品信息"];
            }
        } failure:^(NSError *error) {
            [self log:[NSString stringWithFormat:@"查询信息失败%@",error.localizedDescription]];
        }];
    }else{
        [self log:@"查询时，传入的商品id为空"];
    }
}


- (void)purchaseProduct:(NSString *)productID{
    [self log:[NSString stringWithFormat:@"购买%@商品",productID]];
    [[RMStore defaultStore]addPayment:productID success:^(SKPaymentTransaction *transaction) {
        NSLog(@"购买成功");
    } failure:^(SKPaymentTransaction *transaction, NSError *error) {
        NSLog(@"购买失败");
    }];
}
- (BOOL)isRemoveAdsUser{
    return NO;
}
- (BOOL)isSubcribeUser{
    return NO;
}
- (void)restorePurchase{
    [self log:@"正在恢复购买项目"];
    [[RMStore defaultStore]restoreTransactionsOnSuccess:^(NSArray *transactions) {
        
    } failure:^(NSError *error) {
        
    }];
    
}
- (void)dealloc
{
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
    [[RMStore defaultStore]removeStoreObserver:self];
}
#pragma mark   payment delegate
- (void)paymentQueue:(nonnull SKPaymentQueue *)queue updatedTransactions:(nonnull NSArray<SKPaymentTransaction *> *)transactions {
    for (SKPaymentTransaction *transaction in transactions) {
        switch (transaction.transactionState) {
            case SKPaymentTransactionStatePurchasing:
                [self log:@"交易正在进行中........."];
                break;
            case SKPaymentTransactionStatePurchased:
                [self log:@"交易完成........."];
                break;
            case SKPaymentTransactionStateFailed:
                [self log:@"交易失败........."];
                break;
            case SKPaymentTransactionStateDeferred:
                [self log:@"交易递延........."];
                break;
            case SKPaymentTransactionStateRestored:
                [self log:@"恢复购买........."];
                break;
        }
    }
}
- (void)paymentQueue:(SKPaymentQueue *)queue updatedDownloads:(NSArray<SKDownload *> *)downloads{
    
}
- (BOOL)paymentQueue:(SKPaymentQueue *)queue shouldAddStorePayment:(SKPayment *)payment forProduct:(SKProduct *)product{
    return YES;
}
- (void)paymentQueue:(SKPaymentQueue *)queue removedTransactions:(NSArray<SKPaymentTransaction *> *)transactions{
    
}
- (void)storeProductsRequestFinished:(NSNotification *)notification{
  
    NSLog(@"====storeProductsRequestFinished:%@",notification.rm_products.description);
}
- (void)storeProductsRequestFailed:(NSNotification *)notification{
    NSLog(@"=====storeProductsRequestFailed");
}
- (void)storePaymentTransactionFinished:(NSNotification *)notification{
//    [notification.rm_products ]
    
}
- (void)storePaymentTransactionFailed:(NSNotification *)notification{
    NSLog(@"");
}

- (void)storePaymentTransactionDeferred:(NSNotification *)notification{
    
}
extern "C"{
    void initPurchase(bool showlog,char *str){
    

        
    }
    void buyProduct(char* productIdentifier){
        
        
        
    }
    void refreshSubsribtionState(){
        
        
    }
}



@end
